package kr.kwakyc.puzzle;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class PuzzleGame {
	
	private Ranking ranking;
	
	private int TILE_SIZE_MIN = 3;
	private int TILE_SIZE_MAX = 10;
	
	public PuzzleGame(){
		ranking = new Ranking();
	}
	
	public void run() {
		
		JFrame frame = new JFrame();
		frame.setLocation(500, 200);
		frame.setPreferredSize(new Dimension(600, 400));
		
		Container container = frame.getContentPane();
		
		JPanel controlPanel = new JPanel();
		
		JLabel lblImagePath = new JLabel("이미지 경로를 입력하세요 : ");
		JTextField tfImagePath = new JTextField(30);
		controlPanel.add(lblImagePath);
		controlPanel.add(tfImagePath);
		
		JLabel lblTileSize = new JLabel("타일 크기를 입력하세요. (3 ~ 10) ");
		JTextField tfTileSize = new JTextField(5);
		controlPanel.add(lblTileSize);
		controlPanel.add(tfTileSize);
		
		JLabel lblLevel = new JLabel("난이도를 선택하세요.");
		JComboBox cbLevel = new JComboBox(Level.getLevelNames());
		cbLevel.setSelectedIndex(0);
		controlPanel.add(lblLevel);
		controlPanel.add(cbLevel);
		
		
		JButton btnGameStart = new JButton("게임 시작");
		JButton btnRanking = new JButton("랭킹 보기");
		btnGameStart.addActionListener(new GameStartActionListener(tfImagePath, tfTileSize, cbLevel));
		btnRanking.addActionListener(new RankingActionListener());
		controlPanel.add(btnGameStart);
		controlPanel.add(btnRanking);
		
		container.add(controlPanel, BorderLayout.CENTER);
		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		frame.pack();
		frame.setVisible(true);
	}
	
	class GameStartActionListener implements ActionListener{
		
		private JTextField tfImagePath;
		private JTextField tfTileSize;
		private JComboBox cbLevel;
		
		
		public GameStartActionListener(JTextField tfImagePath, JTextField tfTileSize, JComboBox cbLevel){
			this.tfImagePath = tfImagePath;
			this.tfTileSize = tfTileSize;
			this.cbLevel = cbLevel;
			
		}
		
		@Override
		public void actionPerformed(ActionEvent e) {
			String filePath = tfImagePath.getText();
			int tileSize = Integer.parseInt(tfTileSize.getText());
			if(tileSize < TILE_SIZE_MIN)		tileSize = TILE_SIZE_MIN;
			else if(tileSize > TILE_SIZE_MAX) 	tileSize = TILE_SIZE_MAX;
			
			String selectedLevel = (String)cbLevel.getSelectedItem();
			Level level = Level.findByStringValue(selectedLevel);
			
			Game game = new Game(filePath, tileSize, level, ranking);
		}
	}
	
	class RankingActionListener implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent e) {
			ranking.show();
		}
	}
}
